import queue as Queue
from threading import Thread,Condition,BoundedSemaphore
from pixiv.file_download import file_download
from config.user_setting import QUERY_THREAD_COUNT,QUERY_THREAD_MEANWHILE_COUNT
class UrlQueue():
    
    def __init__(self):
        self.q = Queue.Queue()
    
    def get(self,timeout=None):
        # if not self.size():
        #     return None
        # 阻塞，如果队列里没有元素,会一直等待
        return self.q.get(timeout=timeout)
    
    def put(self,item):
        self.q.put(item)
    
    def size (self):
        return self.q.qsize()

class Queue_thread_url(Thread):
    def __init__(self,queue,sema,pixiv):
        super(Queue_thread_url,self).__init__()
        self.lock = Condition()
        self.q = queue
        self.pixiv = pixiv
        self.sema=sema
    def run(self):
        with self.sema:
            while(True):
                url = ""
                self.lock.acquire()
                try:
                    url = self.q.get(timeout=3) 
                    print(url)
                except Queue.Empty:
                    print('未取到URL')
                    return None
                finally:
                    self.lock.release()
                d = file_download(url,self.pixiv)
                d.auto_select_download()

class Queue_thread_download():
    '''
    使用队列下载
    '''
    def __init__(self,s,queue):
        self.s= s
        self.queue = queue
        threadnum = QUERY_THREAD_MEANWHILE_COUNT
        self.sema = BoundedSemaphore(threadnum)
    def queue_download(self):
        lis = []
        for i in range(QUERY_THREAD_COUNT):
            print(i,'号线程创建完成')
            t = Queue_thread_url(self.queue,self.sema,self.s)
            t.setDaemon(False)
            t.start()
            lis.append(t)    